package labb3.FileHandling;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import java.io.File;

/**
 * Class giving methods to show "open file" or "save file" window.
 *
 * @author Mikko Puustinen
 * @version 0.5, 2007-okt-18
 */
public class FileChooser {
    private final JFileChooser chooser;
    private final JFrame frame;
    private String path = "";

    /**
     * Creates a JFileChooser object. Will not show anything on the screen.
     *
     * @param frame parent to the FileChooser. This will determine the
     *              look-and-feel of the FileChooser and the position of the
     *              window.
     *
     * @see javax.swing.JFileChooser
     */
    public FileChooser(JFrame frame) {
        this.frame = frame;
        chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.setFileFilter(new XMLFileFilter());
        chooser.setFileFilter(new SerializedFileFilter());
    }

    /**
     * Pops up an "open file" file chooser dialog.
     *
     * @return the absolute path to the selected file. Returns null if no file
     *         was selected (the window was closed).
     *
     * @throws Exception if something is wrong with the path.
     */
    public String openDialog() throws Exception {
        String p = null;

        int r = chooser.showOpenDialog(frame);
        if (r == 0) {
            try {
                p = chooser.getSelectedFile().getPath();
            }
            catch (Exception ie) {
                throw new Exception("Error in determining path");
            }
        }

        return p;
    }

    /**
     * Pops up an "save as" file saver dialog.
     *
     * @return the absolute path to the selected file. Returns null if no file
     *         was selected (the window was closed).
     */
    @SuppressWarnings({"AssignmentToNull"})
    public String saveAs() {
        String p;

        int result = chooser.showSaveDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            MediaFileFilter filter = (MediaFileFilter)chooser.getFileFilter();
            String ext = filter.getExtension(file);
            if (ext == null)
                p = file.getPath() + "." + filter.getFilterExtension();
            else
                p = file.getPath();
            path = p;
        } else {
            p = null;
        }

        return p;
    }

    /**
     * Returns the path to the latest saved or opened file.
     *
     * @return path to the last opened or saved file.
     */
    public String getPath() {
        return path;
    }
}